// com.example.demo.proxy.MyServiceProxyFactory
package com.rain.rainspringboot3.beanDefinitionRegistrar.proxy;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyServiceProxyFactory implements FactoryBean<Object> {

    private final Class<?> targetClass;

    public MyServiceProxyFactory(String className) {
        try {
            this.targetClass = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("无法加载类: " + className, e);
        }
    }

    @Override
    public Object getObject() throws Exception {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(new MyMethodInterceptor());
        return enhancer.create();
    }

    @Override
    public Class<?> getObjectType() {
        return targetClass;
    }

    @Override
    public boolean isSingleton() {
        return true; // 通常代理是单例
    }

    // 自定义拦截逻辑
    public static class MyMethodInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("【代理前置】调用方法: " + method.getName());
            try {
                Object result = proxy.invokeSuper(obj, args);
                System.out.println("【代理后置】方法执行成功");
                return result;
            } catch (Exception e) {
                System.out.println("【代理异常】" + e.getMessage());
                throw e;
            }
        }
    }
}